#! usr/bin/python 
import time
import os

def mini():
    dic={}
    with open('genecode.gtf') as fgtf:
        for lines in fgtf.readlines():
            line2=lines.split('\t')

            if line2[2]=='gene':
                newlist=[] 
                #new gene,new key list
                gene_name_cod=line2[8].split('"')[7]   
                chr_cod,start,end,sign=[line2[i] for i in [0,3,4,6]]  
                #print(chr_cod,start,end,sign)
                for li in [chr_cod,start,end,sign]:
                    newlist.append(li)

            ex=[]
            if line2[2]=='exon':
                exon={}
                line2_eight=line2[8].split('"')
                #gene_name_exon,
                exon_num=line2_eight[16].split(';')[1].strip()
                e_start,e_end=line2[3:5]

                for e in [e_start,e_end]:
                    ex.append(e) 
                    #one exon one dict inside the list,the exon num of the gene is key,the position of exon is value,outside of the dict gene name is key,the the other is value
                exon[exon_num]=ex 

                newlist.append(exon)
            dic[gene_name_cod]=newlist

    key_list=list(dic.keys())

    #print (dic.keys(),len(dic)) 

#sortBed -i  noncoding.bed > noncoding_sort.bed
#sortBed -i  min_protein_coding.gtf > min_protein_coding_sort.gtf

    #with open('min_protein_coding_sort.gtf') as fcod:
        #fcod_read=fcod.read()
        #fcod_split=fcod_read.split('\n')
        #foverlap=open('overlap_res.txt','w')
      
    with open('noncoding_sort.bed') as flnc:
        #s=0
        k=0
        for lnc in flnc.readlines()[0:1]:
            k=k+1
            print (k)
            lnc_sp=lnc.split('\t')

            lnc_start=int(lnc_sp[1])
            lnc_end=int(lnc_sp[2])
            lnc_dire=lnc_sp[-1].strip('\n')

            for i in range(0,1):
                #print (key_list[i],key_list[i+1])
                two_line_0=dic[key_list[i]]
                two_line_1=dic[key_list[i+1]]

                #print (two_line_0[4]['exon_number 1'],two_line_1)
                last_start,last_end=two_line_0[1],two_line_0[2]
                next_start,next_end=two_line_1[1],two_line_1[2]
                print(last_start,next_start)
                '''

                if lnc.split('\t')[0]==two_line[0].split('\t')[0]: #the first 
                    # last_start=int(two_line[0].split('\t')[1])
                    # last_end=int(two_line[0].split('\t')[2])
                    # next_start=int(two_line[1].split('\t')[1])
                    # next_end=int(two_line[1].split('\t')[2])
                    dire_left=two_line[0].split('\t')[3]
                    dire_right=two_line[1].split('\t')[3]
                    if (lnc_start > last_end) and (lnc_end < next_start): #no overlap (bidirectioanal or intergenic)
                        s=i
                        dis_left=lnc_start - last_end
                        dis_right=next_start - lnc_end
                        min_dis=min(dis_left,dis_right)
                        if min_dis < 1000: 
                            if min_dis == dis_left:
                                if not lnc_dire == dire_left: #directioanl is 
                                    foverlap.write('Bidirectional\t'+lnc.strip('\n')+'\t'+two_line[0].strip('\n')+'\t'+two_line[1]+'\n')
                                else:
                                    foverlap.write('Intergenic\t'+lnc.strip('\n')+'\t'+two_line[0].strip('\n')+'\t'+two_line[1]+'\n')
                            if min_dis == dis_right:
                                if not lnc_dire == dire_right:
                                    foverlap.write('Bidirectional\t'+lnc.strip('\n')+'\t'+two_line[0].strip('\n')+'\t'+two_line[1]+'\n')
                                else:
                                    foverlap.write('Intergenic\t'+lnc.strip('\n')+'\t'+two_line[0].strip('\n')+'\t'+two_line[1]+'\n')
                        else:
                            foverlap.write('Intergenic\t'+lnc.strip('\n')+'\t'+two_line[0].strip('\n')+'\t'+two_line[1]+'\n')
                        break

                    else: #sense or antisense (judge direction)
                        if ((lnc_start < last_end) and (lnc_end > last_start)): #overlap with left
                            s=i
                            # print (lnc_dire,dire_left)
                            if lnc_dire == dire_left:
                                foverlap2.write(lnc.strip('\n')+'\t'+two_line[0]+'\n')
                                foverlap.write('sense\t'+lnc.strip('\n')+'\t'+two_line[0]+'\t'+two_line[1]+'\n')
                            else:
                                foverlap.write('antisense\t'+lnc.strip('\n')+'\t'+two_line[0]+'\t'+two_line[1]+'\n')
                            break 





#sortBed -i  gene_exon.bed > gene_exon_sort.bed
#sortBed -i  allsense.bed> allsense_sort.bed


def exon():
    m=0
    
    fsense=open('allsense_sort.bed')
    f_exon=open('gene_exon_sort.bed')
    fexon_read=f_exon.read()
    fexon_split=fexon_read.split('\n')

    s=4250
    for line in fsense.readlines()[0:13076]:
        m=m+1
        print ('m: '+str(m))
        cod_gene=line.split('\t')[10].strip('\n')
        chr_cod=line.split('\t')[0]
  
        for j in range(s,1044648):
            exon_line=fexon_split[j]
            
            if exon_line.split('\t')[0]==chr_cod: #same chr 
                if exon_line.split('\t')[3]==cod_gene: #same gene
                    lnc_start=line.split('\t')[1]
                    lnc_end=line.split('\t')[2]
                    lnc_name1=line.split('\t')[3]
                    lnc_name2=line.split('\t')[4]

                    exon_start=exon_line.split('\t')[1]
                    exon_end=exon_line.split('\t')[2]

                    if (lnc_end>exon_start) and (lnc_start<exon_end):
                        with open('exonic.txt','a') as fwei:
                            fwei.write(lnc_name1+'\t'+lnc_name2+'\t'+'exon'+'\n')
                        break
                        print ('j: '+str(j))
                        s=j
                    else:
                        pass
                        print ('j: '+str(j))
                        s=j
    fsense.close()
    f_exon.close()


def tiqu():
    fei=open('exonic_intronic_antisense_Intergenic_Bidirectional.txt','w')
    all_exon=[]
    fexon=open('exonic.txt')
    for exon in fexon.readlines()[0:]:
        all_exon.append(exon.split('\t')[0])

    allsense=[]
    fallsense=open('allsense_sort.bed')
    for sense_gene in fallsense.readlines():
        allsense.append(sense_gene.split('\t')[3])

    for sense in allsense:
        if sense in all_exon:
            fei.write(sense+"\texonic\n")
        else:
            fei.write(sense+"\tintronic\n")

    fcr=open('overlap_res.txt')
    antisense=[]
    Intergenic=[]
    Bidirectional=[]
    for cr in fcr.readlines():
        if cr.split('\t')[0]=='antisense':
            antisense.append(cr.split('\t')[4])
        if cr.split('\t')[0]=='Intergenic':
            Intergenic.append(cr.split('\t')[4])
        if cr.split('\t')[0]=='Bidirectional':
            Bidirectional.append(cr.split('\t')[4])

    for anti in antisense:
        fei.write(anti+"\tantisense\n")
    for Inter in Intergenic:
        fei.write(Inter+"\tIntergenic\n")
    for Bid in Bidirectional:
        fei.write(Bid+"\tBidirectional\n")

    fei.close()

'''




if __name__ == '__main__':
    start_time=time.clock()
    
    mini()
    # os.system("sortBed -i  noncoding.bed > noncoding_sort.bed")
    # os.system("sortBed -i  min_protein_coding.gtf > min_protein_coding_sort.gtf")

    # overlap()

    # coding()
    # os.system("sortBed -i  gene_exon.bed > gene_exon_sort.bed")
    # os.system("sortBed -i  allsense.bed> allsense_sort.bed")

    #exon()

    # tiqu()

    end_time=time.clock()
    time_used=end_time-start_time
    print(time_used)


